/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-28
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 添加好友页面
 */
import 'package:flutter/material.dart';
import 'package:chat_client/config/api_config.dart';
import 'package:chat_client/services/user_service.dart';
import 'package:chat_client/services/contact_service.dart';
import 'package:chat_client/widgets/global_widgets.dart';
import 'package:chat_client/models/user.dart';

import 'friend_aplly.dart';

class AddFriendScreen extends StatefulWidget {
  const AddFriendScreen({Key? key}) : super(key: key);

  @override
  AddFriendScreenState createState() => AddFriendScreenState();
}

class AddFriendScreenState extends State<AddFriendScreen> {
  final ContactService _contactService = ContactService.instance;
  final UserService _userService = UserService.instance;
  final TextEditingController _searchController = TextEditingController();

  User? _searchResults;
  bool _isLoading = false;
  bool _canAdd = false;
  String _message = '';

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _handleSearch() async {
    final searchText = _searchController.text.trim();
    if (searchText.isEmpty) return;
    setState(() {
      _isLoading = true;
    });

    try {
      final results = await _contactService.searchUser(searchText);
      setState(() {
        _searchResults = User.fromJson(results['user']);
        _canAdd = results['canAdd'];
        _message = results['message'] ?? '';
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isLoading = false;
      });
      _showError(e.toString());
    }
  }

  void _showError(String message) {
    if (!mounted) return;
    showDialog(
      context: context,
      builder: (context) => CustomErrorDialog(
        title: '发送申请失败',
        message: message,
      ),
    );
  }

  Widget _buildSearchResult() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    if (_searchResults == null) {
      return const Center(child: Text('未找到用户'));
    }

    return UserDetailCard(
      user: _searchResults!,
      canAdd: _canAdd,
      message: _message,
      onSendRequest: () => _handleSendRequest(_searchResults!),
    );
  }

  Future<void> _handleSendRequest(User user) async {
    if (!_canAdd) return _showError(_message);

    final localUser = await _userService.getLocalUserInfo();
    if (!mounted) return;

    showDialog(
      context: context,
      builder: (context) {
        return CustomInputDialog(
          title: '发送好友申请',
          hintText: '你好!我是${localUser['nickname']}',
          onSend: (input) async {
            try {
              final response = await _contactService.sendFriendRequest(
                contact: _searchResults,
                applyInfo: input,
              );
              if (mounted) {
                Navigator.pop(context);
                ScaffoldMessenger.of(context)
                    .showSnackBar(SnackBar(content: Text(response)));
              }
            } catch (e) {
              _showError(e.toString());
            }
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加好友'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          _buildQuickAccess(),
          _buildSearchSection(),
          Expanded(child: _buildSearchResult()),
        ],
      ),
    );
  }

  Widget _buildQuickAccess() {
    return Column(
      children: [
        customListInfo(
            title: '好友申请',
            icon: Icons.person_add,
            backgroundColor: Colors.amber,
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => const FriendApplicationScreen()),
              );
            }),
        buildDivider(),
        customListInfo(
            title: '黑名单',
            icon: Icons.block,
            backgroundColor: Colors.black,
            onTap: () {}),
      ],
    );
  }

  Widget _buildSearchSection() {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: TextField(
        controller: _searchController,
        decoration: InputDecoration(
          labelText: '账号/手机号',
          suffixIcon: IconButton(
            icon: const Icon(Icons.search),
            onPressed: _handleSearch,
          ),
          contentPadding: const EdgeInsets.only(left: 16.0),
        ),
        onSubmitted: (_) => _handleSearch(),
      ),
    );
  }
}

class UserDetailCard extends StatelessWidget {
  final User user;
  final bool canAdd;
  final String message;
  final VoidCallback onSendRequest;

  const UserDetailCard({
    Key? key,
    required this.user,
    required this.canAdd,
    required this.message,
    required this.onSendRequest,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        customUserInfo(
          title: user.nickname,
          subtitle: '账号: ${user.username}',
          imageUrl: baseUrl + user.avatarUrl,
          size: 60,
        ),
        buildDivider(indent: 0, height: 20),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  const SizedBox(width: 20),
                  Icon(
                    user.gender == 0 ? Icons.male : Icons.female,
                    color: Colors.grey[600],
                  ),
                  const SizedBox(width: 10),
                  Text(user.gender == 0 ? '男' : '女'),
                  const SizedBox(width: 24),
                  if (user.birthday.isNotEmpty) Text('生日: ${user.birthday}'),
                ],
              ),
              const SizedBox(height: 20),
              if (user.signature.isNotEmpty) Text(user.signature),
            ],
          ),
        ),
        buildDivider(indent: 0, height: 20),
        Column(
          children: [
            _buildActionButton(
              canAdd ? '发送好友申请' : message,
              Icons.person_add,
              canAdd ? onSendRequest : null,
            ),
            buildDivider(indent: 0),
            _buildActionButton('加入黑名单', Icons.block, () {}),
          ],
        ),
      ],
    );
  }

  Widget _buildActionButton(String text, IconData icon, VoidCallback? onTap) {
    return TextButton.icon(
      icon: Icon(icon, color: Colors.grey[600]),
      label: Text(text),
      onPressed: onTap,
      style: TextButton.styleFrom(
        minimumSize: const Size(double.infinity, 48),
        foregroundColor: onTap != null ? Colors.blue : Colors.grey,
      ),
    );
  }
}

class CustomInputDialog extends StatefulWidget {
  final String title;
  final String hintText;
  final Function(String) onSend;

  const CustomInputDialog({
    Key? key,
    required this.title,
    required this.hintText,
    required this.onSend,
  }) : super(key: key);

  @override
  CustomInputDialogState createState() => CustomInputDialogState();
}

class CustomInputDialogState extends State<CustomInputDialog> {
  final TextEditingController _inputController = TextEditingController();

  @override
  void dispose() {
    _inputController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Center(child: Text(widget.title)),
      content: TextField(
        controller: _inputController,
        decoration: InputDecoration(hintText: widget.hintText),
        maxLines: 3,
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () {
            final text = _inputController.text.trim();
            widget.onSend(text.isNotEmpty ? text : widget.hintText);
            Navigator.pop(context);
          },
          child: const Text('发送'),
        ),
      ],
    );
  }
}
